package cn.qiguai.sphapi.service.impl;

import cn.qiguai.sphapi.controller.request.GetPageOrderParam;
import cn.qiguai.sphapi.controller.response.Page;
import cn.qiguai.sphapi.domain.Addressee;
import cn.qiguai.sphapi.domain.GoodsCategorySaleAttrsValue;
import cn.qiguai.sphapi.domain.ShoppingCartOrder;
import cn.qiguai.sphapi.domain.User;
import cn.qiguai.sphapi.mapper.AddresseeMapper;
import cn.qiguai.sphapi.mapper.ShoppingCartOrderMapper;
import cn.qiguai.sphapi.mapper.UserMapper;
import cn.qiguai.sphapi.service.UserService;
import cn.qiguai.sphapi.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashSet;
import java.util.List;
import java.util.UUID;

@Service
@Transactional
public class UserServiceImpl implements UserService {
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private ShoppingCartOrderMapper shoppingCartMapper;
	@Autowired
	private AddresseeMapper addresseeMapper;

	@Override
	public boolean register(User u) {
		//密码加密
		String password = u.getPassword();
		String salt = UUID.randomUUID().toString().replaceAll("-", "");
		String md5Password = DigestUtils.md5DigestAsHex((password + salt).getBytes());
		u.setSalt(salt);
		u.setPassword(md5Password);

		return userMapper.insertUser(u) != 0;
	}

	@Override
	public String login(User u) {
		//查询用户
		User user = userMapper.selectUser(u.getPhoneNumber());

		//账号不存在
		if (user == null) {
			return null;
		}

		//将登陆密码重新加密并与数据库密码比较
		String md5Password = DigestUtils.md5DigestAsHex((u.getPassword() + user.getSalt()).getBytes());
		if (!md5Password.equals(user.getPassword())) { //密码不相同
			return null;
		}

		u.setId(user.getId());

		//密码相同，生成token
		return JWTUtils.getToken(u);
	}

	@Override
	public boolean existPhoneNumber(String phoneNumber) {
		return userMapper.selectUser(phoneNumber) != null;
	}

	/**
	 * 判断是否加入过相同商品
	 * @param info info
	 * @return true：加入过 false：未加入过
	 */
	private boolean existShoppingCartOrder(ShoppingCartOrder info) {
		boolean flag = false;

		//获取所有相同用户id、商品id的订单
		List<ShoppingCartOrder> orders = shoppingCartMapper.selectShoppingCartOrderByUserIdAndGoodsId(info.getUserId(), info.getGoodsId());
		for (ShoppingCartOrder order : orders) {
			//获取订单的商品属性
			List<GoodsCategorySaleAttrsValue> saleAttrs = shoppingCartMapper.selectGoodsAttrs(order.getId());

			//判断商品属性是否全部相同和是否已购买
			if (saleAttrs.size() == info.getSaleAttrs().size() && order.isStatus() == info.isStatus() && new HashSet<>(saleAttrs).containsAll(info.getSaleAttrs())) {
				flag = true;
				info.setId(order.getId());
				break;
			}
		}

		return flag;
	}

	@Override
	public boolean addToShoppingCart(ShoppingCartOrder info) {
		//加入过相同商品
		if (existShoppingCartOrder(info)) {
			return shoppingCartMapper.updateShoppingCartOrderAmount(info.getId(), info.getAmount()) != 0;
		}

		return shoppingCartMapper.saveOrderInfo(info) != 0 && shoppingCartMapper.saveGoodsAttrs(info.getId(), info.getSaleAttrs()) != 0;
	}

	@Override
	public Page<ShoppingCartOrder> getPageShoppingCartOrder(GetPageOrderParam param) {
		//计算分页开始索引
		int startIndex = (param.getCurrentPage() - 1) * param.getPageSize();

		//查询搜索商品总数量
		int totalCount = shoppingCartMapper.pageSelectOrderCount(param.getUserId());

		if (totalCount == 0) {
			return new Page<>();
		}

		//查询商品列表
		List<ShoppingCartOrder> orderList = shoppingCartMapper.pageSelectOrder(param, startIndex);
		for (ShoppingCartOrder order : orderList) {
			order.setSaleAttrs(shoppingCartMapper.selectGoodsAttrs(order.getId()));
		}

		Page<ShoppingCartOrder> page = new Page<>();

		page.setCurrentPage(param.getCurrentPage());
		page.setPageSize(param.getPageSize());
		page.setTotalCount(totalCount);
		page.setData(orderList);
		page.computeHasNext();

		return page;
	}

	@Override
	public boolean selectOneShoppingCartOrder(int orderId) {
		return shoppingCartMapper.updateOneOrderChecked(orderId) != 0;
	}

	@Override
	public boolean selectAllShoppingCartOrder(int userId, boolean flag) {
		return shoppingCartMapper.updateAllOrderChecked(userId, flag) != 0;
	}

	@Override
	public boolean removeShoppingCartOrder(List<Integer> ids) {
		return shoppingCartMapper.removeShoppingCartOrderSaleAttrs(ids) != 0 && shoppingCartMapper.removeShoppingCartOrder(ids) != 0;
	}

	@Override
	public List<Addressee> getAddresseeInfo(int userId) {
		return addresseeMapper.getAddresseeInfo(userId);
	}
}
